package com.czkt.springboot_mybatis_test.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@WebFilter(filterName = "AutoFilter",urlPatterns = "/*")
public class AutoFilter implements Filter {
    public StringRedisTemplate getRedisTemplate() {
        return stringRedisTemplate;
    }

    public void setRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        Set<String> filterUrl = new HashSet<>();
        filterUrl.add("/springboot_mybatis_test/sys-user/login");
        filterUrl.add("/springboot_mybatis_test/sys-user/doLogin");
        filterUrl.add("/springboot_mybatis_test/sys-user/logout");
        if((session.getAttribute("loginUser") != null || stringRedisTemplate.opsForValue().get("loginUser") != null) || filterUrl.contains(request.getServletPath()) || request.getServletPath().endsWith(".css")){
            if (session.getAttribute("loginUser") == null && stringRedisTemplate.opsForValue().get("loginUser") != null){
                JSONObject jsonObject = (JSONObject) JSON.parse(stringRedisTemplate.opsForValue().get("loginUser"));
                System.out.println(stringRedisTemplate.opsForValue().get("loginUser"));
                session.setAttribute("loginUser",jsonObject);
            }
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            response.sendRedirect("/springboot_mybatis_test/sys-user/login");
        }
    }

    @Override
    public void destroy() {
    }
}
